package com.example.chuntiao.cophook.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.adapter.CompOrg;
import com.example.chuntiao.cophook.adapter.OrgAdapter;
import com.example.chuntiao.cophook.beans.Choice;
import com.example.chuntiao.cophook.beans.Org;
import com.example.chuntiao.cophook.beans.OrgDataSupport;
import com.example.chuntiao.cophook.enums.UpdateState;
import com.example.chuntiao.cophook.exception.LogInException;
import com.example.chuntiao.cophook.exception.NewUserException;
import com.example.chuntiao.cophook.exception.NoNetException;
import com.example.chuntiao.cophook.mytools.ArrPolisher;
import com.example.chuntiao.cophook.mytools.HttpTool;
import com.example.chuntiao.cophook.mytools.MyApp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by chuntiao on 17-7-17.
 */

public class OrgFragment extends Fragment {

    private MyApp myApp;
    private static final String TAG = "OrgFragment";
    private OrgAdapter mOrgAdapter;
    final static int REQ_FOR_ORGDETAIL_ACTI = 1;

    public OrgFragment() {

        Log.d(TAG, "OrgFragment: 重新建立+++++++++++++++++++++++++++++++++++++++++++");
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQ_FOR_ORGDETAIL_ACTI && resultCode == RESULT_OK) {
            new LoadDataTask(true).execute();
            ((PersionFragment) ((MainActivity) getActivity()).personFragment).new LoadDataTask(true).execute();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        myApp = (MyApp) getActivity().getApplication();
        Log.d(TAG, "onCreateView: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        View rootView = inflater.inflate(R.layout.fragment_base, container, false);
        RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rec_theList);

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        //LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        mOrgAdapter = new OrgAdapter();
        recyclerView.setAdapter(mOrgAdapter);
        mOrgAdapter.setOnClickListener(new OrgAdapter.OnOrgClickListener() {

            int limitTime;
            @Override
            public void onClickPic(View v, int position) {
                Org org = mOrgAdapter.getmOrgList().get(position);
                Intent intent = new Intent(v.getContext(), OrgDetail.class);
                intent.putExtra("invitNum", org.getInvitNum());
                intent.putExtra("oid", org.getOid());
                intent.putExtra("oname", org.getOname());
                intent.putExtra("img_ver", org.getImgVer());
                intent.putExtra("intro", org.getIntro());

                startActivityForResult(intent, REQ_FOR_ORGDETAIL_ACTI);
            }

            @Override
            public void onClickMore(View v, int position) {
                /*final boolean[] change=new boolean[]{false};
                final Org o = mOrgAdapter.getmOrgList().get(position);

                BottomDialog bottomDialog=new BottomDialog(v.getContext(),R.layout.bottom_dialog_person);
                View view=bottomDialog.getRootView();
                final NumberPicker picker=(NumberPicker) view.findViewById(R.id.num_picker);
                TextView txtOname=(TextView)view.findViewById(R.id.txt_oname);


                txtOname.setText(o.getOname());
                picker.setMinValue(1);
                picker.setMaxValue(200);
                picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        change[0]=false;
                        limitTime=newVal;
                    }
                });


                bottomDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if(change[0]){
                            new AsyncTask<Void,Void,Boolean>(){
                                AlertDialog alertDialog;
                                @Override
                                protected void onPreExecute() {
                                    alertDialog=new AlertDialog.Builder(getContext())
                                            .setPositiveButton(R.string.yse,null)
                                            .setMessage("更新信息失败")
                                            .create();
                                }


                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    try {
                                        UpdateState state= HttpTool.sendOkHttpUpDateOrg(getActivity(),
                                                HttpTool.CODE_UPDATE_INVITE_LIMIT_TIME,o,limitTime);
                                        return UpdateState.FAIL!=state;
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    return false;
                                }

                                @Override
                                protected void onPostExecute(Boolean result) {
                                    if(!result){
                                        alertDialog.show();
                                    }
                                    else {
                                        alertDialog=null;
                                        Snackbar.make(((MainActivity)getActivity()).fab,"信息更新完成",Snackbar.LENGTH_SHORT).show();
                                        new LoadDataTask(true).execute();//更新本地数据库
                                    }
                                }
                            }.execute();
                        }


                    }
                });
                bottomDialog.show();*/
            }
        });

        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreate: ___________________________________________________________________");
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new LoadDataTask().execute();
    }


    public OrgAdapter getAdapter() {
        return mOrgAdapter;
    }


    public class LoadDataTask extends AsyncTask<Void, Void, ArrayList<Org>> {

        final int SUCCESS = 0;
        final int NO_NET = 1;
        final int WRONG_PASS = 2;
        final int NEW_USER = 3;
        int state = SUCCESS;
        boolean sureFromNet = false;


        LoadDataTask(boolean fromNet) {
            super();
            this.sureFromNet = fromNet;
        }

        LoadDataTask() {
            super();
        }


        void readFromLocal(ArrayList<Org> empList) {

            List<OrgDataSupport> orgs = DataSupport.findAll(OrgDataSupport.class);
            for (OrgDataSupport org : orgs) {
                empList.add(new Org(org));
            }
        }

        int readFromNet(ArrayList<Org> emptyListOrg, ArrayList<Choice> emptyListChoice) {
            String jsonStrOrg = null;
            String jsonStrChoice;
            try {
                jsonStrOrg = HttpTool.sendOkHttpRequest(getActivity(), HttpTool.CODE_ORGS, null);
                jsonStrChoice = HttpTool.sendOkHttpRequest(getActivity(), HttpTool.CODE_ACCESSIBLE_CHOICES, null);

                Gson gson = new Gson();
                ArrayList<Org> newArgList = gson.fromJson(jsonStrOrg, new TypeToken<ArrayList<Org>>() {
                }.getType());
                for (Org o : newArgList) {
                    emptyListOrg.add(o);
                }

                ArrayList<Choice> newChoiceList = gson.fromJson(jsonStrChoice, new TypeToken<ArrayList<Choice>>() {
                }.getType());
                for (Choice c : newChoiceList) {
                    emptyListChoice.add(c);
                }

                return SUCCESS;

            } catch (ConnectException e) {
                e.printStackTrace();
                return NO_NET;
            } catch (NoNetException e) {
                return NO_NET;
            } catch (NewUserException e) {
                return NEW_USER;
            } catch (LogInException e) {
                return WRONG_PASS;
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }

        }

        @Override
        protected ArrayList<Org> doInBackground(Void... params) {
            ArrayList<Org> orgArrayList = new ArrayList<>();
            ArrayList<Choice> choiceList = new ArrayList<>();

            if (sureFromNet || myApp.timeToSyn()) {
                state = readFromNet(orgArrayList, choiceList);
                if (state == SUCCESS) {
                    ArrPolisher.checkContentAndSaveOrg(orgArrayList);
                    ArrPolisher.checkContentAndSaveChoice(choiceList);
                }
            } else
                readFromLocal(orgArrayList);
            if (state != SUCCESS)
                readFromLocal(orgArrayList);//从网络读取失败后，从本地读

            Collections.sort(orgArrayList, new CompOrg());
            //myApp.setOrgArrayList(orgArrayList);
            return orgArrayList;
        }

        @Override
        protected void onPostExecute(ArrayList<Org> orgs) {

            mOrgAdapter.setmOrgList(orgs);
            mOrgAdapter.notifyDataSetChanged();
        }
    }


}
